local skynet = require "skynet"
local log = require "sky_log"

local SOCKET = {}
local gate
local agent = {}

local function close_agent(fd)
	local a = agent[fd]
	agent[fd] = nil

	if a then
		skynet.call(gate, "lua", "closeclient", fd)
		-- disconnect never return
		skynet.send(a, "lua", "disconnect")
	end
end

function SOCKET.open(fd, addr)
	log.info("New client from : " .. addr)
	agent[fd] = skynet.newservice("handle_websocket_agent")
	skynet.call(agent[fd], "lua", "start", { gate=gate, client=fd, watchdog=skynet.self() })
end

function SOCKET.close(fd)
	log.info("watchdog SOCKET.close fd=", fd)
	close_agent(fd)
end

function SOCKET.error(fd, msg)
	log.info("watchdog SOCKET.error fd=", fd)
	log.info("watchdog SOCKET.error msg=", msg)

	close_agent(fd)
end

function SOCKET.warning(fd, size)
	log.info("watchdog SOCKET.warning fd=", fd)
	log.info("watchdog SOCKET.warning size=", size)

	-- size K bytes havn't send out in fd
end

function SOCKET.data(fd, msg)
	log.info("watchdog SOCKET.data fd=", fd)
	log.info("watchdog SOCKET.data msg=", msg)
end



--============================= CMD =============================--
local CMD = {}

function CMD.start(conf)
	skynet.call(gate, "lua", "open" , conf)
end

function CMD.close(fd)
	close_agent(fd)
end

function CMD.query_tables()
	log.info("watchdog query_tables agent=", agent)
end

skynet.start(function()
	skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
		if cmd == "socket" then
			local f = SOCKET[subcmd]
			f(...)
			-- socket api don't need return
		else
			local f = assert(CMD[cmd])
			skynet.ret(skynet.pack(f(subcmd, ...)))
		end
	end)

	gate = skynet.newservice("handle_websocket_gate", socket_type)
end)
